package com.zhx.sweet;

import com.zhx.sweet.common.properties.OAuth2ClientProperties;
import com.zhx.sweet.common.properties.SecurityProperties;
import com.zhx.sweet.exception.CustomOauth2Exception;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.Arrays;

/**
 * @author zhanghaixuan
 * @create 2017/12/10-下午5:20
 * 继承AuthorizationServerConfigurerAdapter 后可以自定义token
 * 如果不继承 就是spring自己实现  如果继承了 全部都要自己写
 * 使用spring oauth 实现认证服务器 EnableAuthorizationServer
 **/
@Configuration
@EnableAuthorizationServer
public class AppAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired(required = false)
    private CustomOauth2Exception customOauth2Exception;

//    @Autowired(required = false)
//    private JwtAccessTokenConverter jwtAccessTokenConverter;
//
//    @Autowired(required = false)
//    private TokenEnhancer jwtTokenEnhancer;

    @Autowired(required = false)
    private TokenEnhancer customTokenEnhancer;

    @Autowired
    private SecurityProperties securityProperties;



    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);


        if(customOauth2Exception != null){
            DefaultWebResponseExceptionTranslator exceptionTransator = customOauth2Exception.getExceptionTransator();

            endpoints.exceptionTranslator(exceptionTransator);
        }



        if(customTokenEnhancer != null){
            final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer));

            endpoints.tokenEnhancer(tokenEnhancerChain);
        }


//        if(jwtAccessTokenConverter!=null && jwtTokenEnhancer!= null
//                ){
//            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
//
//            List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
//
//            tokenEnhancers.add(jwtTokenEnhancer);
//            tokenEnhancers.add(jwtAccessTokenConverter);
//
//            tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
//
//            endpoints
//                    .tokenEnhancer(tokenEnhancerChain)
//                    .accessTokenConverter(jwtAccessTokenConverter);
//        }
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if (ArrayUtils.isNotEmpty(securityProperties.getoAuth2Properties().getClients())) {
            for (OAuth2ClientProperties client : securityProperties.getoAuth2Properties().getClients()) {
                builder.withClient(client.getClientId())
                        .secret(client.getClientSecret())
                        .authorizedGrantTypes("refresh_token")
                        .accessTokenValiditySeconds(client.getAccessTokenValidateSeconds())
                        .refreshTokenValiditySeconds(client.getAccessTokenValidateSeconds()*2)
                        .scopes(client.getClientId());
            }
        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
    }
}
